package edu.suda.LoopCodePlus.webSocket;


import com.fasterxml.jackson.databind.ObjectMapper;
import edu.suda.LoopCodePlus.entity.User;
import edu.suda.LoopCodePlus.entity.UserExtra;
import edu.suda.LoopCodePlus.service.UserService;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Component
@ServerEndpoint(value = "/myWS")
public class HttpAuthHandler extends TextWebSocketHandler {
    @Autowired
    private UserService userService;
    @Autowired
    private RunSingleMatch runSingleMatch;

    /**
     * socket 建立成功事件
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("用户连接:"+session.getId());
        System.out.println("用户uri:"+session.getUri());
        Integer userId = Integer.valueOf(session.getUri().getQuery().split("=")[1]);
        System.out.println(userId);

        System.out.println("用户"+userId+"连接成功");
        if (userId != null) {
            // 用户连接成功，放入在线用户缓存
            User user= userService.findUserById(userId);
            UserExtra userExtra=userService.findUserExtraById(userId);
            if(WsSessionManager.add(userExtra.getSinPoint(),userId, session)==1){
                System.out.println("用户"+user.getUserId()+"加入匹配连接池成功");
                int addR=WsSessionManager.addRoom(userExtra.getSinPoint(),userId, session);
                if(addR==1){
                    System.out.println("匹配人数充足,进行对战,房间号："+userId);
                    //匹配成功后，向房间中的每个用户发送消息
                    HashMap<Integer,WebSocketSession> room=WsSessionManager.getRoom(userId);
                    for(Integer id:room.keySet()){
                        room.get(id).sendMessage(new TextMessage("{\"code\":0,\"roomId\":"+userId+"}"));
                    }
                } else if (addR==2) {
                    //session.sendMessage(new TextMessage("2"));
                }
            }
            else{
                System.out.println("用户"+user.getUserId()+"加入连接池失败");
                session.sendMessage(new TextMessage("0"));
            }
        } else {
            throw new RuntimeException("用户登录已经失效!");
        }

    }

    /**
     * 接收消息事件
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获得客户端传来的消息
        String payload = message.getPayload();
        System.out.println(payload);
        //解析payload
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> jsonObject=new HashMap<>();
        try {
            jsonObject = objectMapper.readValue(payload,Map.class);
            System.out.println("信息解析成功:"+jsonObject);
            Integer code=(Integer) jsonObject.get("code");
            Integer roomId=(Integer) jsonObject.get("roomId");
            HashMap<Integer,WebSocketSession> room=WsSessionManager.getRoom(roomId);
            System.out.println("房间号:"+roomId);
            if(code==1){
                Integer userId=(Integer) jsonObject.get("userId");
                for (Integer id:room.keySet()){
                    if(Objects.equals(id, userId)) room.get(id).sendMessage(new TextMessage("{\"code\":1,\"problemId\":65}"));
                }
            }else if(code==2){
                String token=(String) jsonObject.get("token");
                Integer userId=(Integer) jsonObject.get("userId");
                String result=runSingleMatch.python(jsonObject,token);
                System.out.println("runSingleMatch返回结果:"+result);
                Map<String,Object> resultObject=new HashMap<>();
                resultObject = objectMapper.readValue(result,Map.class);
                List res =(List) resultObject.get("result");
                Integer point=(Integer) res.get(3);
                //WsSessionManager.print();
                for(Integer id:room.keySet()){
                    if(Objects.equals(id, userId)){
                        room.get(id).sendMessage(new TextMessage(result));
                    }
                    else {
                        if(point>0) room.get(id).sendMessage(new TextMessage("{\"code\":2,\"point\":"+point+"}"));
                    }
                }
                if(point==100){
                    WsSessionManager.removeAndClose(roomId);
                    WsSessionManager.print();
                }
            }
        } catch (Exception e) {
            // 处理异常
            System.out.println(e.getMessage());
            System.out.println("解析异常");
        }

    }

    /**
     * socket 断开连接时
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object userId = session.getAttributes().get("userId");
        if (userId != null) {
            // 用户退出，移除缓存
            WsSessionManager.removeAndClose((Integer) userId);
        }
        System.out.println("server 断开连接 " + userId);
    }
}


